package com.xuhai.blog19.admin.controller;

import com.xuhai.blog19.admin.entity.UserEntity;
import com.xuhai.blog19.admin.form.PasswordForm;
import com.xuhai.blog19.admin.service.UserService;
import com.xuhai.blog19.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author PangJunjie
 * @Date 2023/2/6/006
 */
@RestController
@RequestMapping("/admin/user")
public class UserController extends AbstractBaseController {

    @Autowired
    private UserService userService;

    @GetMapping("/login/info")
    public R loginInfo() {
        return R.ok().data(getUser());
    }

    @GetMapping("/page")
    public R page(int page, int limit, UserEntity user) {
        return R.ok().data(userService.getPage(page, limit, user));
    }

    @PostMapping("/update")
    public R update(@RequestBody UserEntity user) {
        userService.saveOrUpdateInfo(user);
        return R.ok();
    }

    @DeleteMapping("/delete/{userId}")
    public R delete(@PathVariable Integer userId) {
        if (userId.equals(getUserId())) {
            return R.error("当前登录用户不能删除");
        }
        if (userId == 1) {
            return R.error("管理员不能删除");
        }
        userService.removeById(userId);
        return R.ok();
    }

    @GetMapping("/info/{userId}")
    public R info(@PathVariable Integer userId) {
        return R.ok().data(userService.getById(userId));
    }

    @PostMapping("/password")
    public R password(@RequestBody PasswordForm passwordForm) {
        passwordForm.setUserId(getUserId());
        userService.updatePassword(passwordForm);
        return R.ok();
    }


}
